/**
 * Created with IntelliJ IDEA.
 * User: Tung An
 * Date: 12/11/13
 * Time: 1:01 AM
 * To change this template use File | Settings | File Templates.
 */

var GridFormat = {
    colCount: 0,
    colWidth: 0,
    spaceLeft: 0,
    margin: 10,
    windowWidth: 0,
    blocks: [],

    formatLayout: function (className, node, margin) {
        var cls = "look-item";
        if (node) {
            this.windowWidth = node.offsetWidth;
        } else {
            this.windowWidth = window.outerWidth;
        }
        if (className) {
            cls = className;
        }
        this.colWidth = $class(cls)[0].offsetWidth;
        this.colCount = Math.floor(this.windowWidth / (this.colWidth + this.margin));
        this.spaceLeft = (this.windowWidth - ((this.colWidth * this.colCount) + (this.margin * (this.colCount - 1)))) / 2;
        for (var i = 0; i < this.colCount; i++) {
            this.blocks.push(this.margin);
        }
        this.positionBlocks(cls);
        window.onresize = function () {
            GridFormat.refreshLayout(cls, node, margin);
        };
    },

    refreshLayout: function (className, node, margin) {
        GridFormat.colCount = 0;
        GridFormat.colWidth = 0;
        GridFormat.spaceLeft = 0;
        if (margin) {
            GridFormat.margin = margin;
        } else {
            GridFormat.margin = 10;
        }
        GridFormat.windowWidth = 0;
        GridFormat.blocks = [];
        GridFormat.formatLayout(className, node, margin);
    },

    positionBlocks: function (cls) {
        var self = this;
        var nodeList = $class(cls);
        var nodes = Array.prototype.slice.call(nodeList, 0);
        nodes.forEach(function (node) {
            var min = Array.min(self.blocks);
            var index = self.blocks.indexOf(min);
            var leftPos = self.margin + (index * (self.colWidth + self.margin));
            node.style.left = (leftPos + self.spaceLeft) + 'px';
            node.style.top = min + 'px';

            self.blocks[index] = min + node.offsetHeight + self.margin;
        });
    }
};
Array.min = function (array) {
    return Math.min.apply(Math, array);
};